package com.lmu.travel.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author liuxuhuang
 * @className: RedisUtil
 * @description: redis工具类
 * @email liuxuhuang3970@qq.com
 * @date 2021/6/28 10:11
 * @version：1.0
 */
@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 写入redis，并设置3分钟过期
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        /**
         *参数分别是key，value，时间，时间单位,这里表示缓存的这个键值对5分钟后失效
         */
        try {
            redisTemplate.opsForValue().set(key, value, 5, TimeUnit.MINUTES);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断该键是否存在
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        if (key.equalsIgnoreCase("null")) {
            return false;
        }
        if (redisTemplate.hasKey(key)) {
            return true;
        }
        return false;
    }

    /**
     * 从redis中读取key值
     */
    public String get(final String key) {
        if (exists(key)) {
            return (String) redisTemplate.opsForValue().get(key);
        }
        return null;
    }

    /**
     * 从redis读取类型为list的key值
     *
     * @param key
     * @return
     */
    public List<Object> getList(final String key) {
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    public boolean setList(final String key, List<Object> list) {
        try {
            redisTemplate.opsForList().leftPushAll(key, list);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 先判断是否存在该键，存在即删除
     *
     * @param key
     * @return
     */
    public boolean delete(final String key) {
        if (redisTemplate.hasKey(key)) {
            if (redisTemplate.delete(key)) {
                return true;
            }
        }
        return false;
    }
}
